package com.app.micaihu.view.newsdetail;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.adapter.NewsCommentAdapter;
import com.app.micaihu.adapter.NewsCommentChildAdapter;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseListActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.comment.CommentDetail;
import com.app.micaihu.bean.comment.NewsComment;
import com.app.micaihu.bean.comment.PariseBean;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.CircleImageOnly;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.GoodView.GoodView;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.CommentListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.CommentUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.view.expression.view.BiaoQinTextView;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 评论详情页面
 * Created by linkai on 2016/8/23.
 */
public class CommentDetailActivity extends BaseListActivity<NewsComment> {

    private CustomImageView mUserImg;//评论头像
    private TextView mUsername;//作者昵称
    private CustomImageView mUserRank;//作者军衔
    private TextView mUserRankText;//作者军衔名称
    private TextView mComZan;//评论赞
    private TextView mComTime;//评论时间
    private BiaoQinTextView mComMesg;//评论内容
    private CustomImageView mNewsImg;//文章图片
    private TextView mNewsTitle;//文章标题
    private TextView mPariseSum;//点赞总数
    private LinearLayout mPariseListView;//评论头像列表

    /********* 页面逻辑变量 ***********/
    private String articleId;//文章id
    private String commentId;//评论id

    /************** 工具 *************/
    private CommentListener mCommentListener;//评论监听
    private CommentDetail commentDetail;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getIntentData();
        super.onCreate(savedInstanceState);
    }

    /**
     * 获取参数
     */
    private void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            articleId = intent.getStringExtra(Config.Extra.PARAMETER1);
            commentId = intent.getStringExtra(Config.Extra.PARAMETER2);
        }
    }

    @Override
    protected void changeView() {
        View headView = LayoutInflater.from(this).inflate(R.layout.layout_comment_detail_head, null);

        mUserImg = (CustomImageView) headView.findViewById(R.id.comment_usericon);
        mUsername = (TextView) headView.findViewById(R.id.comment_username);
        mUserRank = (CustomImageView) headView.findViewById(R.id.comment_rank);
        mComZan = (TextView) headView.findViewById(R.id.comment_zan);
        mComTime = (TextView) headView.findViewById(R.id.comment_time);
        mComMesg = (BiaoQinTextView) headView.findViewById(R.id.comment_message);
        mNewsImg = (CustomImageView) headView.findViewById(R.id.comment_news_img);
        mNewsTitle = (TextView) headView.findViewById(R.id.comment_news_title);
        mUserRankText = (TextView) headView.findViewById(R.id.comment_rank_name);
        View titleLayout = headView.findViewById(R.id.comment_news_layout);
        titleLayout.setOnClickListener(this);
        mComMesg.setOnClickListener(this);
        mUserImg.setOnClickListener(this);
        mUsername.setOnClickListener(this);
        mComZan.setOnClickListener(this);

        //添加头部view
        mListView.getRefreshableView().addHeaderView(headView);

        //添加底部评论
        if (flCommonBottom != null) {
            View view = this.getLayoutInflater().inflate(R.layout.layout_imagecomment_bottom, null);
            flCommonBottom.addView(view);
            flCommonBottom.setOnClickListener(this);
        }

        //是否展示评论引导页面
        if (AppConfigManager.getInstance().readConfig(ConfigKeyConstant.firstshow_commment, true)) {
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.FIT_END);
            imageView.setImageResource(R.drawable.guide_comment);
            imageView.setBackgroundColor(getResources().getColor(R.color.common_black_transparent50per));
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(layoutParams);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v != null) {
                        v.setVisibility(View.GONE);
                    }
                }
            });
            mContentView.addView(imageView);
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.firstshow_commment, false);
        }
    }

    @Override
    protected void changeData(final boolean isRefresh) {

        HashMap<String, String> parmsMap = new HashMap<String, String>();
        parmsMap.put("articleId", articleId);
        parmsMap.put("page", dataPage + "");
        parmsMap.put("commentId", commentId);
        HttpListener<DataBean<CommentDetail>> httpListener = new HttpListener<DataBean<CommentDetail>>() {

            @Override
            public void onStart() {
//                updateLoadView(LOADING,null);
                setLoadView(LOADING, null);
            }

            @Override
            public void onError(VolleyError error) {
//                updateLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror_click));
                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror_click));
            }

            @Override
            public void onSuccess(DataBean<CommentDetail> response) {
                if (response.noError()) {
                    CommentDetail commentDetail = response.getData();
                    if (commentDetail != null) {
                        setCommentData(commentDetail);
                        if (dataList == null) {
                            dataList = new ArrayList<NewsComment>();
                        }
                        List<NewsComment> list = commentDetail.getChildList();
                        if (list != null && list.size() > 0) {
                            //数据去重
                            if (isRefresh) {
                                dataList.clear();
                                //在第一个位置添加最新评论
                                NewsComment comment = new NewsComment();
                                comment.setCommentTypeName("全部评论");
                                dataList.add(0, comment);
                            }
                            //追加数据集合
                            dataList.addAll(list);
                        }
                        if (mAdapter == null) {
                            if (dataList.size() == 0) {
                                dataList.add(null);
                            }
                            mAdapter = new NewsCommentChildAdapter(dataList, mActivity);
                            mListView.setAdapter(mAdapter);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }
//                        updateLoadView(LOADSUCES, null);
                        setLoadView(LOADSUCES, null);
                    } else {
//                        updateLoadView(DATAERROR, response.getErrorMsg());
                        setLoadView(DATAERROR, response.getErrorMsg());
                    }
                } else {
//                    updateLoadView(DATAERROR, response.getMsg());
                    setLoadView(DATAERROR, response.getMsg());
                }
            }
        };
        addPostCacheRequest(URIContant.NEWSCOMMENTDETAIL, new TypeToken<DataBean<CommentDetail>>() {
        }.getType(), parmsMap, httpListener);
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.comment_zan://点赞
                laud(view);
                break;
            case R.id.comment_message://点击回复内容
                showCommentDialog();
                break;
            case R.id.comment_news_layout://点击新闻
                toNewsDetail();
                break;
            case R.id.comment_username://点击头像
            case R.id.comment_usericon://点击昵称
                if (commentDetail == null) {
                    return;
                }
                Intent intent = new Intent(this, MyHomepageDynamicActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, commentDetail.getUid());
                startActivity(intent);
                break;
            case R.id.fl_common_bottom://点击底部评论框
                showCommentDialog();
                break;
            case R.id.comment_parise_layout://跳转点赞列表
                if (commentDetail == null) {
                    return;
                }
                Intent intent1 = new Intent(this, CommentPariseActivity.class);
                intent1.putExtra(Config.Extra.PARAMETER1, commentDetail.getArticleId());
                intent1.putExtra(Config.Extra.PARAMETER2, commentDetail.getId());
                startActivity(intent1);
                break;
        }
    }

    /**
     * 跳转新闻详情
     */
    private void toNewsDetail() {
        if (commentDetail == null) {
            return;
        }
        NewsEntity newsEntity = new NewsEntity();
        newsEntity.setArticleId(commentDetail.getArticleId());
        newsEntity.setArticleType(commentDetail.getArticleType());
        TypeConstant.openTypeDetail(newsEntity, this, "");
    }

    /* 展示评论框 */
    private void showCommentDialog() {
        if (mCommentListener == null) {
            mCommentListener = new CommentListener() {
                @Override
                public void commentStart() {

                }

                @Override
                public void commentFail(VolleyError volley) {

                }

                @Override
                public void commentSuccess(NewsComment newsComment) {
                    //更新页面
                    if (newsComment == null) {
                        return;
                    }
                    if (dataList == null) {
                        dataList = new ArrayList<NewsComment>();
                    }
                    if (dataList.size() == 0) {
                        //在第一个位置添加最新评论
                        NewsComment comment = new NewsComment();
                        comment.setCommentTypeName("全部评论");
                        dataList.add(0, comment);
                    }
                    dataList.add(1, newsComment);
                    if (mAdapter == null) {
                        mAdapter = new NewsCommentChildAdapter(dataList, mActivity);
                        mListView.setAdapter(mAdapter);
                    } else {
                        mAdapter.notifyDataSetChanged();
                    }
                }
            };
        }
        CommentUtils.getInstance().showDialog(this, mPageName, articleId, commentDetail, mCommentListener);
    }

    private GoodView mGoodView;//点赞PopupWindow

    /**
     * 点赞
     */
    private void laud(View view) {
        if (commentDetail == null) {
            return;
        }
        if (Boolean.valueOf(view.getTag().toString())) {
            ToastUtils.makeText("您已经赞过");
            return;
        }
        //提前改变点赞效果以及点赞成功数据(点赞伪成功)
        TextView tv = (TextView) view;
        view.setSelected(true);
        String zanNum = (StringUtils.toInt(tv.getText().toString(), 0) + 1) + "";
        tv.setText(zanNum);
        commentDetail.setPraiseNum(zanNum);
        NewsCommentAdapter.getZanList().add(commentDetail.getId());
        if (mGoodView == null) {
            mGoodView = new GoodView(this);
        }
        mGoodView.setTextInfo("+1", Color.parseColor("#e55d5d"), 12);
        mGoodView.show(view);
        view.setTag(true);
        //将头像添加到点赞列表中
        if (mPariseListView == null) {
            mPariseListView = (LinearLayout) findViewById(R.id.comment_zan_list);
        }
        if (UserInforManager.getInstance().isLogin() && mPariseListView.getChildCount() < 5) {

            if (mPariseListView.getVisibility() == View.GONE) {
                mPariseListView.setVisibility(View.VISIBLE);
            }
            UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
            CircleImageOnly circleImageOnly = new CircleImageOnly(this, userInfor.getHeadPic(), 32);
            mPariseListView.addView(circleImageOnly, 0);
            circleImageOnly.setTag(userInfor.getUid());
//            circleImageOnly.setPadding(6,0,6,0);


            LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) circleImageOnly.getLayoutParams();
            layoutParams1.rightMargin = ViewSizeUtils.dp2px(this, 5);
            circleImageOnly.setLayoutParams(layoutParams1);


            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v == null || v.getTag() == null) {
                        return;
                    }
                    String uid = v.getTag().toString();
                    Intent intent = new Intent(CommentDetailActivity.this, MyHomepageDynamicActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1, uid);
                    startActivity(intent);
                }
            };
            circleImageOnly.setOnClickListener(onClickListener);
        }

        //请求点赞网络操作
        ParamMap parmsMap = new ParamMap();
        //请求点赞网络操作
        if (UserInforManager.getInstance().isLogin()) {
            parmsMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());

        } else {
            parmsMap.putEncode("uid", "0");

        }
        parmsMap.putEncode("type", "1");
        parmsMap.putEncode("articleId", commentDetail.getArticleId());
        parmsMap.putEncode("toUid", commentDetail.getUid());
        parmsMap.putEncode("commentId", commentDetail.getId());
        parmsMap.putEncode("operateType", "0");
        parmsMap.putEncode("parentCmtId", "0");
        HttpUtils.ParmsMapMD5(parmsMap);

        HttpListener<DataBean> httpListener = new HttpListener<DataBean>() {
            @Override
            public void onError(VolleyError error) {
                ToastUtils.makeText("onError");
            }

            @Override
            public void onSuccess(DataBean response) {
                if (response.noError()) {
                    String sql = "insert into " + NewsDBSqlHelper.COMMENT_ZAN + " values (" + commentDetail.getId() + ")";
                    NewsDBUtil.getInstance().changeData(sql);
                }
            }
        };

        //请求网络
        HttpUtils.addPostRequest(URIContant.NEWS_ZAN, new TypeToken<DataBean>() {
        }.getType(), null, parmsMap, httpListener);

        //设置返回的数据  返回时通知变化数据
        setResult(RESULT_OK);
    }

    /**
     * 设置评论数据
     */
    private void setCommentData(CommentDetail comDetail) {
        if (commentDetail != null) {
            //如果已经初始化过了则 不再初始化
            return;
        }
        this.commentDetail = comDetail;
        LoadImageUtils.getInstance().loadCircleImage(mUserImg, commentDetail.getHeadPic());
        mUsername.setText(commentDetail.getNickName());
        mUserRankText.setText(commentDetail.getRankName());
        mComZan.setText(commentDetail.getPraiseNum());
        //判断是否点赞过
        if (NewsCommentAdapter.getZanList().contains(commentDetail.getId())) {
            mComZan.setSelected(true);
            mComZan.setTag(true);
            if (UserInforManager.getInstance().isLogin()) {
                //如果登录了则把用户头像加入到第一个位置
                UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
                PariseBean pariseBean = new PariseBean();
                pariseBean.setHeadPic(userInfor.getHeadPic());
                pariseBean.setNickName(userInfor.getNickName());
                pariseBean.setUid(userInfor.getUid());
                commentDetail.getPraiseList().add(0, pariseBean);
            }

        } else {
            mComZan.setSelected(false);
            mComZan.setTag(false);
        }
        mComTime.setText(commentDetail.getPublishTime());
        mNewsTitle.setText("[" + commentDetail.getCommentTypeName() + "]" + commentDetail.getArticleTitle());
        if (commentDetail.getArticleThumb() != null && commentDetail.getArticleThumb().length > 0) {
            LoadImageUtils.getInstance().loadImage(mNewsImg, commentDetail.getArticleThumb()[0]);
        }
        LoadImageUtils.getInstance().loadImage(mUserRank, commentDetail.getRankIcon());
        mComMesg.setPicText(commentDetail.getContent());
        //设置点赞列表
        List<PariseBean> pariseBeanList = commentDetail.getPraiseList();
        if (pariseBeanList == null || pariseBeanList.size() == 0) {
            return;
        }
        if (mPariseListView == null) {
            mPariseListView = (LinearLayout) findViewById(R.id.comment_zan_list);
        }
        View pariseLayout = findViewById(R.id.comment_parise_layout);
        pariseLayout.setVisibility(View.VISIBLE);
        pariseLayout.setOnClickListener(this);
        findViewById(R.id.commont_zan_driver).setVisibility(View.VISIBLE);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == null || v.getTag() == null) {
                    return;
                }
                String uid = v.getTag().toString();
                Intent intent = new Intent(CommentDetailActivity.this, MyHomepageDynamicActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, uid);
                startActivity(intent);
            }
        };
        for (int i = 0; i < pariseBeanList.size(); i++) {

            PariseBean pariseBean = pariseBeanList.get(i);
            if (pariseBean == null) {
                continue;
            }
            if (i != 0 && UserInforManager.getInstance().isLogin() &&
                    TextUtils.equals(UserInforManager.getInstance().getUserInfor().getUid(), pariseBean.getUid())) {
                //如果当前点赞用户和本地登录用户uid一样,则跳过
                continue;
            }
            CircleImageOnly circleImageOnly = new CircleImageOnly(this, pariseBean.getHeadPic(), 32);
            mPariseListView.addView(circleImageOnly);
            circleImageOnly.setTag(pariseBean.getUid());
            LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) circleImageOnly.getLayoutParams();
            layoutParams1.rightMargin = ViewSizeUtils.dp2px(this, 5);
            circleImageOnly.setLayoutParams(layoutParams1);
            circleImageOnly.setOnClickListener(onClickListener);
            if (mPariseListView.getChildCount() > 4) {
                break;
            }
        }
        mPariseSum = (TextView) findViewById(R.id.comment_zan_sum);
        mPariseSum.setText(commentDetail.getPraiseNum() + "个人赞过");

    }

}
